<?php

namespace App\Services\MakeBoxProductOrder;

use App\Models\User;
use App\Models\Product;
use App\Models\Address;
use App\Models\UserCoupon;
use App\Models\BlindBox;
use App\Models\BlindBoxProduct;
use App\Models\BlindBoxLevelValue;
use App\Models\ProductSku;
use Brick\Math\RoundingMode;
use App\Events\OrderCreatedEvent;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;


class MakeBoxProductOrder
{
	protected ?User $user = null;

	protected ?Address $address = null;

	protected ?BlindBox $blindBox = null;

	/**
	 * sku_id, attr_value_index, amount.
	 */

	public function __construct(
		User $user,
		Address $address,
		BlindBox $blindBox,
		$userCouponId = 0,
	    )
	{
		$this->user = $user;
		$this->address = $address;
		$this->blindBox = $blindBox;
		$this->userCouponId = $userCouponId;
	}

	protected function create()
	{
		DB::transaction(function () {


			$blindBoxProduct = $this->getRandomProduct();
			$product  = Product::find($blindBoxProduct->product_id);
			$sku  = $product->skus->first();

			$couponPrice = 0;
			if($this->userCouponId){
				$coupon = UserCoupon::find($this->userCouponId)->coupon()->first();
				$couponPrice = $coupon->decrement_price;

			}
			$insertArr = [
				'user_id' => $this->user->id,
				'product_id' => $blindBoxProduct->product_id,
				'sku_id' => $sku->id,
				'box_price' => $this->blindBox->price,
				'cost' => $product->price_lowest_cost,
				'profit' => big_decimal($this->blindBox->price)->minus($product->price_lowest_cost)->minus($couponPrice),
				'create_at' => date("Y-m-d Hi:i:s",time()),
				'blind_box_id' => $this->blindBox->id,
				'address_id' => $this->address->id,
				'blind_box_level_id' => $blindBoxProduct->blind_box_level_id,
				'user_coupon_id' => $this->userCouponId,
			];
			
			$this->order = $this->user->blindBoxOrders()->create($insertArr);

		});

		return $this->order;
	}

	public function getRandomProduct(){ 
		$levels = BlindBoxLevelValue::query()->used()->where('blind_box_id',$this->blindBox->id)->get();

		$merge = [];
		foreach($levels as $k => $v){

			$fill = array_fill(0,($v->rate*100),$v->blind_box_level_id);
			$merge = array_merge($merge,$fill);
		}
		
		$num=rand(0,count($merge));

		$level = $merge[$num];

		$blindBoxProduct = BlindBoxProduct::query()
						->where('blind_box_id',$this->blindBox->id)
						->where('blind_box_level_id',$level)
						->inRandomOrder()
						->take(1)->first();
		
		return $blindBoxProduct;
	}
	
	public function make()
	{
		return $this->create();
	}
}
